import requests

from analyze.xpath_analyzer import decode_response

from download.sub.zhiXiaoBin_downloader import zhiXiaoBinDownloader
from handle.handler import BasicHandler
from analyze.xpath_analyzer import XpathAnalyzer

import logging
import traceback
from store.sub.zhiXiaoBin import zhiXiaoBinProjectStore


class zhiXiaoBinProjectHandler(BasicHandler):
    def __init__(self, config):
        super(zhiXiaoBinProjectHandler, self).__init__(config)
        self.mdb = config['mdb']

    def get_downloader(self):
        return zhiXiaoBinDownloader(self.config)

    def get_analyzer(self):
        return XpathAnalyzer(self.config)

    def get_store(self):
        return zhiXiaoBinProjectStore(self.config)

    def duplicated_key(self, task):
        return 'duplicated:{}:{}'.format(self.name, task['project_id'])

    def save(self, result, task):
        try:
            result['project_id'] = task['project_id']
            self.store.set(self.store.table, result)
            self.mdb.commit()
        except Exception as e:
            logging.error(e)
            logging.error(traceback.format_exc())









def get_detail(company_id):
    url = 'http://wx.zhixiaobing.com/weixin/search/company_details.html'
    headers = {}
    headers['Host'] = 'wx.zhixiaobing.com'
    headers['Upgrade-Insecure-Requests'] = '1'
    headers[
        'User-Agent'] = 'Mozilla/5.0 (Linux; Android 9; Redmi 8A Build/PKQ1.190319.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045426 Mobile Safari/537.36 MMWEBID/9808 MicroMessenger/7.0.20.1781(0x2700143E) Process/tools WeChat/arm32 NetType/4G Language/zh_CN ABI/arm32'
    headers[
        'Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
    headers['X-Requested-With'] = 'com.tencent.mm'
    headers['Referer'] = 'http://wx.zhixiaobing.com/weixin/index/index.html'
    headers['Accept-Encoding'] = 'gzip, deflate'
    headers['Accept-Language'] = 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7'
    headers['Cookie'] = 'PHPSESSID=ffa3fcba3c84a90598c0410d217cac5c'
    params = {
        'id': company_id
    }
    r = requests.get(url, headers=headers, params=params)
    return r

